package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gulimall
 * @description:
 * @author: 江天赐
 * @create: 2022-08-19 21:08
 */
@Configuration
public class MyRabbitConfig {
    /**
     * 使用json序列化机制，进行消息转换
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    //需要监听，否则RabbitMQ不会自动创建
//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void handle(Message message) {
//
//    }

    /**
     * 创建一个Topic(允许路由键模式匹配)类型名为stock-event-exchange的交换机，
     * 持久，不自动删除
     *
     * @return
     */
    @Bean
    public Exchange stockEventExchange() {
        //String name, boolean durable, boolean autoDelete, Map<String, Object> arguments)
        return new TopicExchange("stock-event-exchange", true, false);
    }

    /**
     * 创建一个stock.release.stock.queue,
     * 持久、是否排他、不自动删除()
     *
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        //String name, boolean durable, boolean exclusive, boolean autoDelete, @Nullable Map<String, Object> arguments
        return new Queue("stock.release.stock.queue", true, false, false);
    }

    /**
     * 创建一个stock.delay.queue的延时队列
     * 持久、是否排他、不自动删除()
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
/**
 * 延时队列，
 *  x-dead-letter-exchange: order-event-exchange
 *  x-dead-letter-routing-key: order.release.order
 *  x-message-ttl: 60000
 */
        Map<String, Object> agrs = new HashMap<>();
        agrs.put("x-dead-letter-exchange", "stock-event-exchange");
        agrs.put("x-dead-letter-routing-key", "stock.release");
        agrs.put("x-message-ttl", 120000L);
        return new Queue("stock.delay.queue", true, false, false, agrs);
    }

    /**
     * stock-event-exchange与stock.release.stock.queue的路由键是
     * 通过stock.release.#
     *
     * @return
     */
    @Bean
    public Binding stockReleaseBinding() {
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }

    /**
     * stock-event-exchange与stock.delay.queue的路由键是
     * 通过stock.locked
     *
     * @return
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }


}
